#include "stdafx.h"
#include "convutil.h"
namespace convutil {
	//Optimized Function to convert an unsigned char to a Hex string of length 2
	void Char2Hex(unsigned char ch, char* szHex)
	{
		static unsigned char saucHex[] = "0123456789ABCDEF";
		szHex[0] = saucHex[ch >> 4];
		szHex[1] = saucHex[ch&0xF];
		szHex[2] = 0;
	}

	//Function to convert a Hex string of length 2 to an unsigned char
	bool Hex2Char(char const* szHex, unsigned char& rch)
	{
		if(*szHex >= '0' && *szHex <= '9')
			rch = *szHex - '0';
		else if(*szHex >= 'A' && *szHex <= 'F')
			rch = *szHex - 55; //-'A' + 10
		else
			//Is not really a Hex string
			return false; 
		szHex++;
		if(*szHex >= '0' && *szHex <= '9')
			(rch <<= 4) += *szHex - '0';
		else if(*szHex >= 'A' && *szHex <= 'F')
			(rch <<= 4) += *szHex - 55; //-'A' + 10;
		else
			//Is not really a Hex string
			return false;
		return true;
	}

	//Function to convert binary string to hex string
	void Binary2Hex(unsigned char const* pucBinStr, int iBinSize, char* pszHexStr)
	{
		int i;
		char szHex[3];
		unsigned char const* pucBinStr1 = pucBinStr;
		*pszHexStr = 0;
		for(i=0; i<iBinSize; i++,pucBinStr1++)
		{
			Char2Hex(*pucBinStr1, szHex);
			strcat(pszHexStr, szHex);
		}
	}

	//Function to convert hex string to binary string
	bool Hex2Binary(char const* pszHexStr, unsigned char* pucBinStr, int iBinSize)
	{
		int i;
		unsigned char ch;
		for(i=0; i<iBinSize; i++,pszHexStr+=2,pucBinStr++)
		{
			if(false == Hex2Char(pszHexStr, ch))
				return false;
			*pucBinStr = ch;
		}
		return true;
	}
}